﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;

namespace Infrastructure.Util
{
    /// <summary>
    /// 数据库配置类
    /// </summary>
    public class DataBaseHelper
    {
        private static string dbFile = ConfigurationManager.AppSettings["data_file"];
        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        /// <returns></returns>
        public static string ConnnectionString()
        {
            SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder();
            string path = Environment.CurrentDirectory + "\\"+ dbFile;
            sb.DataSource = path;
            return sb.ToString();
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static void InitDataBase()
        {
            string path = Environment.CurrentDirectory + "\\"+dbFile;
            if (!File.Exists(path))
            {
                //初始化数据库
                SQLiteConnection.CreateFile(path);
                CreateTables();
            }
        }
        /// <summary>
        /// 初始化表格
        /// </summary>
        private static void CreateTables()
        {
            using (SQLiteConnection db = 
                new SQLiteConnection(ConnnectionString()))
            {
                db.Open();
                string sql = @"CREATE TABLE Users (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name varchar(20),
  account varchar(30),
  password varchar(30),
  createtime datetime
); ";
                SQLiteCommand command = new SQLiteCommand(sql, db);
                command.ExecuteNonQuery();
            }
        }
    }
}
